package com.xing.ucenter.controller;


import com.google.gson.Gson;
import com.xing.servicebase.exceptionhandler.GuliException;
import com.xing.ucenter.entity.Member;
import com.xing.ucenter.entity.RefreshToken;
import com.xing.ucenter.service.MemberService;
import com.xing.ucenter.utils.ConstantPropertiesUtil;
import com.xing.ucenter.utils.HttpClientUtils;
import com.xing.ucenter.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;


@CrossOrigin
@RestController //注意这里不要设置@RestController 不用返回json数据
@RequestMapping("/api/ucenter/wx1")
public class RefreshTokenController {

    @Autowired
    private ConstantPropertiesUtil constantPropertiesUtil;

    @Autowired
    private MemberService ucenterMemberService;


    //刷新token
    @GetMapping("refreshtoken")
    public RefreshToken getRefreshtoken(String refresh_token) {
        try {
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="
                    + constantPropertiesUtil.getAppId() + "&grant_type=refresh_token" +
                    "&refresh_token=" + refresh_token;
            String accessTokenInfo = HttpClientUtils.get(baseAccessTokenUrl);
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String) mapAccessToken.get("access_token");
            Double expires_in = (Double) mapAccessToken.get("expires_in");
            String refreshtoken1 = (String) mapAccessToken.get("refresh_token");
            String openid = (String) mapAccessToken.get("openid");
            String scope = (String) mapAccessToken.get("scope");

            RefreshToken refreshToken = new RefreshToken();
            refreshToken.setAccessToken(access_token);
            refreshToken.setExpiresIn(expires_in);
            refreshToken.setRefreshToken(refreshtoken1);
            refreshToken.setOpenid(openid);
            refreshToken.setScope(scope);

            System.out.println(refreshToken);
            return refreshToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "刷新失败");
        }
    }

}
